package source

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/cookiejar"
	"net/url"
	"regexp"
	"strings"
	"time"

	"google.golang.org/appengine"
	"google.golang.org/appengine/urlfetch"
)

//设置用户名和密码常量
const (
	USERNAME string = "XXX"
	PASSWORD string = "********"
)

func getFormhash(client *http.Client) string {
	urlStr := "http://xhbbs.njit.edu.cn/bbs/portal.php"
	req, err := http.NewRequest("GET", urlStr, nil)
	CheckErr(err)
	res, err := client.Do(req)
	CheckErr(err)
	defer res.Body.Close()
	input, err := ioutil.ReadAll(res.Body)
	CheckErr(err)
	content := Decode(input)
	r := regexp.MustCompile(`name="formhash" value=".*?" />`)
	formhash := r.FindString(content)
	formhash = strings.Replace(formhash, `name="formhash" value="`, "", 1)
	formhash = strings.Replace(formhash, `" />`, "", 1)
	return formhash
}

func post(client *http.Client, form url.Values, urlStr string) string {
	req, err := http.NewRequest("POST", urlStr, bytes.NewBufferString(form.Encode()))
	req.Header.Set("Content-Type", "application/x-www-form-urlEncoded") //设定Content-Type，post参数才可正常传递。
	CheckErr(err)
	res, err := client.Do(req)
	CheckErr(err)
	defer res.Body.Close()
	input, err := ioutil.ReadAll(res.Body)
	CheckErr(err)
	return Decode(input)
}

//Xhbbs 发帖主程序
func Xhbbs(res http.ResponseWriter, req *http.Request) {
	//设置client和cookiejar
	cookieJar, _ := cookiejar.New(nil)
	// client := &http.Client{Jar: cookieJar}//用于本地
	//登录并获取cookie，下次访问时会自动带上cookie
	c := appengine.NewContext(req)
	client := urlfetch.Client(c) //用于gae
	client.Jar = cookieJar
	form := url.Values{ //登录的postdata
		"loginfield":  {"username"},
		"username":    {Encode([]byte(USERNAME))},
		"answer":      {},
		"password":    {PASSWORD},
		"questionid":  {"0"},
		"cookietime":  {"2592000"},
		"loginsubmit": {"true"},
		"formhash":    {getFormhash(client)},
	}
	urlStr := "http://xhbbs.njit.edu.cn/bbs/member.php?mod=logging&action=login&loginsubmit=yes&loginhash=L4hBp&inajax=1"
	content := post(client, form, urlStr)
	r := regexp.MustCompile(`欢迎您回来`)
	if r.MatchString(content) {
		fmt.Fprintln(res, "登录成功！")
	} else {
		fmt.Fprintln(res, "登录失败！")
	}

	//签到
	form = url.Values{ //签到的postdata
		"qdxq":      {"yl"},
		"qdmode":    {"3"},
		"todaysay":  {},
		"fastreply": {"1"},
		"formhash":  {getFormhash(client)},
	}
	urlStr = "http://xhbbs.njit.edu.cn/bbs/plugin.php?id=dsu_paulsign:sign&operation=qiandao&infloat=1&inajax=1"
	content = post(client, form, urlStr)
	r = regexp.MustCompile(`恭喜你签到成功`)
	if r.MatchString(content) {
		fmt.Fprintln(res, "签到成功！")
	} else {
		fmt.Fprintln(res, "已经签到或签到失败！")
	}

	//发帖——段子
	s := strings.Fields(time.Now().String())
	subject := s[0] + ":段子"
	message := Joke("http://neihanshequ.com/joke/", req)
	//fmt.Fprintln(res, message)
	form = url.Values{ //发帖的postdata
		"subject":     {Encode([]byte(subject))},
		"message":     {Encode([]byte(message))},
		"topicsubmit": {"yes"},
		"tags":        {Encode([]byte("机器人-段子"))},
		"formhash":    {getFormhash(client)},
	}

	//发帖的请求URL
	urlStr = "http://xhbbs.njit.edu.cn/bbs/forum.php?mod=post&action=newthread&fid=35&extra=&topicsubmit=yes"
	content = post(client, form, urlStr)
	fmt.Fprintln(res, "已发帖，成功与否未知！")

	//等待30s，发帖——简书
	time.Sleep(time.Second * 30)
	subject = s[0] + ":文章（转自简书）"
	message = Jianshu("http://www.jianshu.com/recommendations/notes", req)
	form = url.Values{ //发帖的postdata
		"subject":     {Encode([]byte(subject))},
		"message":     {Encode([]byte(message))},
		"topicsubmit": {"yes"},
		"tags":        {Encode([]byte("机器人-简书"))},
		"formhash":    {getFormhash(client)},
	}
	//fmt.Fprintln(res, message)
	content = post(client, form, urlStr)
	fmt.Fprintln(res, "已发帖，成功与否未知！")

	//等待30s，发帖——囧图
	time.Sleep(time.Second * 30)
	subject = s[0] + ":囧图"
	message = Pic("http://neihanshequ.com/pic/", req)
	form = url.Values{ //发帖的postdata
		"subject":     {Encode([]byte(subject))},
		"message":     {Encode([]byte(message))},
		"topicsubmit": {"yes"},
		"tags":        {Encode([]byte("机器人-囧图"))},
		"formhash":    {getFormhash(client)},
	}
	content = post(client, form, urlStr)
	fmt.Fprintln(res, "已发帖，成功与否未知！")

}
